package com.ruoyi.energy.service.impl;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.exception.CustomException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.energy.domain.NyMeterAccount1;
import com.ruoyi.energy.domain.NyMeterAccount2;
import com.ruoyi.energy.domain.QyEnterprise;
import com.ruoyi.energy.domain.vo.NyMeterAccountExcelVO1;
import com.ruoyi.energy.mapper.NyMeterAccount1Mapper;
import com.ruoyi.energy.mapper.NyMeterAccount2Mapper;
import com.ruoyi.energy.service.INyCheckMeterService;
import com.ruoyi.energy.service.INyMeterAccount2Service;
import com.ruoyi.energy.service.IQyEnterpriseService;
import com.ruoyi.omp.api.domain.NyCheckMeter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 仪台账运营Service业务层处理
 *
 * @author cjie
 * @date 2022-02-25
 */
@Service
@Slf4j
public class NyMeterAccount2ServiceImpl implements INyMeterAccount2Service {
    @Autowired
    private NyMeterAccount2Mapper nyMeterAccount2Mapper;

    @Autowired
    private NyMeterAccount1Mapper nyMeterAccount1Mapper;

    @Autowired
    private IQyEnterpriseService qyEnterpriseService;

    @Autowired
    private INyCheckMeterService nyCheckMeterService;

    /**
     * 查询仪台账运营
     *
     * @param id 仪台账运营ID
     * @return 仪台账运营
     */
    @Override
    public NyMeterAccount2 selectNyMeterAccount2ById(String id) {
        NyMeterAccount2 account2 = nyMeterAccount2Mapper.selectNyMeterAccount2ById(id);
        //查询抄表记录
        NyCheckMeter nyCheckMeter = new NyCheckMeter();
        nyCheckMeter.setMeterId(id);
        nyCheckMeter.setCurrentCheckDate(account2.getCurrentCheckDate());
        nyCheckMeter.setCurrentValue(account2.getCurrentValue());
        List<NyCheckMeter> list =  nyCheckMeterService.selectNyCheckMeterList(nyCheckMeter);
        if(list != null && list.size()>0){
            account2.setLastValue(list.get(0).getLastValue());
        }else {
            account2.setLastValue(BigDecimal.ZERO);
        }

        return account2;
    }

    @Override
    public NyMeterAccount2 selectNyMeterAccount2ByMeterNum(NyMeterAccount2 nyMeterAccount2) {
        // 扫码获取抄表信息
        List<NyMeterAccount2> result = nyMeterAccount2Mapper.selectNyMeterAccount2List(nyMeterAccount2);
        NyMeterAccount2 account2 = null;
        if(result !=null && result.size()>0){
            //获取当前月份，查询抄表记录，如果存在，设置当前值和上期读数
            //不存在，查询最新抄表记录，上期读数设置为最新抄表记录的当前值
            account2 = result.get(0);
            NyCheckMeter nyCheckMeter = new NyCheckMeter();
            nyCheckMeter.setMeterId(account2.getId());
            List<NyCheckMeter> list =  nyCheckMeterService.selectNyCheckMeterList(nyCheckMeter);
            if(list != null && list.size()>0){
                try {
                    Date firstDay =  DateUtils.getFirstDayOfMonth();
                    if(list.get(0).getFeeCycle() !=null && list.get(0).getFeeCycle().equals(firstDay)){
                        account2.setLastValue(list.get(0).getLastValue());
                        account2.setCurrentValue(list.get(0).getCurrentValue());
                    }else{
                        account2.setLastValue(list.get(0).getCurrentValue());
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }else {
                account2.setLastValue(BigDecimal.ZERO);
            }
        }else{
            log.info("扫码没有获取仪表数据：" + nyMeterAccount2.getMeterNum());
        }
        return account2;
    }

    /**
     * 查询仪台账运营列表
     *
     * @param nyMeterAccount2 仪台账运营
     * @return 仪台账运营
     */
    @Override
    public List<NyMeterAccount2> selectNyMeterAccount2List(NyMeterAccount2 nyMeterAccount2) {
        List<NyMeterAccount2> result = nyMeterAccount2Mapper.selectNyMeterAccount2List(nyMeterAccount2);
        for(NyMeterAccount2 account2:result){
            //查询最新抄录入记录
            NyCheckMeter nyCheckMeter = new NyCheckMeter();
            nyCheckMeter.setMeterId(account2.getId());
            nyCheckMeter.setCurrentCheckDate(account2.getCurrentCheckDate());
            nyCheckMeter.setCurrentValue(account2.getCurrentValue());
            List<NyCheckMeter> list =  nyCheckMeterService.selectNyCheckMeterList(nyCheckMeter);
            if(list != null && list.size()>0){
                account2.setLastValue(list.get(0).getLastValue());
            }else {
                account2.setLastValue(BigDecimal.ZERO);
            }
        }
        return result;
    }

    /**
     * 新增仪台账运营
     *
     * @param nyMeterAccount2 仪台账运营
     * @return 结果
     */
    @Override
    public int insertNyMeterAccount2(NyMeterAccount2 nyMeterAccount2) {
        return nyMeterAccount2Mapper.insertNyMeterAccount2(nyMeterAccount2);
    }

    /**
     * 修改仪台账运营
     *
     * @param nyMeterAccount2 仪台账运营
     * @return 结果
     */
    @Override
    public int updateNyMeterAccount2(NyMeterAccount2 nyMeterAccount2) {
        return nyMeterAccount2Mapper.updateNyMeterAccount2(nyMeterAccount2);
    }

    /**
     * 批量删除仪台账运营
     *
     * @param ids 需要删除的仪台账运营ID
     * @return 结果
     */
    @Override
    public int deleteNyMeterAccount2ByIds(String[] ids) {
        return nyMeterAccount2Mapper.deleteNyMeterAccount2ByIds(ids);
    }

    /**
     * 删除仪台账运营信息
     *
     * @param id 仪台账运营ID
     * @return 结果
     */
    @Override
    public int deleteNyMeterAccount2ById(String id) {
        return nyMeterAccount2Mapper.deleteNyMeterAccount2ById(id);
    }

    @Override
    public String importData(List<NyMeterAccountExcelVO1> nyCableVOList, String meterType) {
        if (StringUtils.isNull(nyCableVOList) || nyCableVOList.size() == 0) {
            throw new CustomException("导入抄表数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        nyCableVOList = nyCableVOList.stream().filter(o-> StringUtils.isNotBlank(o.getMeterNum())).collect(Collectors.toList());
        this.insertDataBatch(nyCableVOList,meterType);
        successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + nyCableVOList.size() + " 条，数据如下：");
        return successMsg.toString();
    }

    @Override
    public List<NyMeterAccount2> selectPrivateNyMeterList(NyMeterAccount2 nyMeterAccount2) {
        NyMeterAccount2 search = new NyMeterAccount2();
        search.setParentId(nyMeterAccount2.getId());
        List<NyMeterAccount2> nyMeterAccounts = nyMeterAccount2Mapper.selectNyMeterAccount2List(search);
        //查询考核表下的私表
        if(nyMeterAccounts.size()>0){
            List<String> assessIds = nyMeterAccounts.stream().map(NyMeterAccount2::getId).collect(Collectors.toList());
            List<NyMeterAccount2> privates = nyMeterAccount2Mapper.selectAccount2ListByParentIds(assessIds);
            return privates;
        }
        return null;
    }
    //查询总表下，所有私表；
    //遍历节点树

    private void insertDataBatch(List<NyMeterAccountExcelVO1> nyCableVOList, String meterType){
        //批量插入数据
        //根据编码查询数据是否存在，存在跳过，不存在插入基础数据，存在更新数据，更新2张表。
        NyMeterAccount1 search1 = new NyMeterAccount1();
        for ( NyMeterAccountExcelVO1 vo1: nyCableVOList) {
            vo1.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
            vo1.setMeterType(meterType);
            search1.setMeterNum(vo1.getMeterNum());
            List<NyMeterAccount1> meterAccount1s = nyMeterAccount1Mapper.selectNyMeterAccount1List(search1);
            if(meterAccount1s !=null && meterAccount1s.size()>0){
                // update account1
                NyMeterAccount1 account1 = covert2Account1(vo1);
                account1.setId(meterAccount1s.get(0).getId());
                nyMeterAccount1Mapper.updateNyMeterAccount1(account1);
                //insert count2
                NyMeterAccount2 meterAccount2s = nyMeterAccount2Mapper.selectNyMeterAccount2ById(account1.getId());
                if(meterAccount2s == null){
                    NyMeterAccount2 account2 = covert2Account2(vo1);
                    account2.setId(meterAccount1s.get(0).getId());
                    nyMeterAccount2Mapper.insertNyMeterAccount2(account2);
                }else{
                    //更新 account2
                    NyMeterAccount2 account2 = covert2Account2(vo1);
                    account2.setId(meterAccount2s.getId());
                    nyMeterAccount2Mapper.updateNyMeterAccount2(account2);
                }
            }else{
                //insert count1
                nyMeterAccount1Mapper.insertNyMeterAccount1(covert2Account1(vo1));
                //count2
                NyMeterAccount2 account2 = covert2Account2(vo1);
                nyMeterAccount2Mapper.insertNyMeterAccount2(account2);
            }
        }

    }

    private NyMeterAccount1 covert2Account1(NyMeterAccountExcelVO1 excelVO1){
        NyMeterAccount1 result = new NyMeterAccount1();
        BeanUtils.copyBeanProp(result,excelVO1);
        if(result.getMagnification() == null){
            result.setMagnification(BigDecimal.ONE);
        }
        if(result.getInitialValue() == null){
            result.setInitialValue(BigDecimal.ZERO);
        }
        return result;
    }

    private NyMeterAccount2 covert2Account2(NyMeterAccountExcelVO1 excelVO1){
        NyMeterAccount2 result = new NyMeterAccount2();
        BeanUtils.copyBeanProp(result,excelVO1);
        if(result.getShareInitialValue() == null){
            result.setShareInitialValue(BigDecimal.ZERO);
        }
        if(result.getCurrentValue() == null){
            result.setCurrentValue(BigDecimal.ZERO);
        }
        if(StringUtils.isNotBlank(result.getCategory()) && result.getCategory().equals("私表")){
            QyEnterprise qy = queryQyEnterpriseByName(result.getEnterpriseName());
            if(qy !=null){
                result.setEnterpriseId(qy.getId());
            }
        }

        //设置 parent
        if(excelVO1.getParentNum() != null){
            NyMeterAccount1 search1 = new NyMeterAccount1();
            search1.setMeterNum(excelVO1.getParentNum());
            List<NyMeterAccount1> parents = nyMeterAccount1Mapper.selectNyMeterAccount1List(search1);
            if(parents !=null && parents.size()>0){
                result.setParentId(parents.get(0).getId());
            }
        }
        return result;
    }

    private QyEnterprise queryQyEnterpriseByName(String name){
        if(name ==null || StringUtils.isBlank(name)){
            return null;
        }
        QyEnterprise qyEnterprise = new QyEnterprise();
        qyEnterprise.setEnterpriseName(name);
        List<QyEnterprise> res = qyEnterpriseService.selectQyEnterpriseList(qyEnterprise);
        if( res == null|| res.size()==0){
            return null;
        }
        return res.get(0);

    }
}
